package com.xsomnus.network_programming.udp;



import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketAddress;
import java.net.SocketException;

/**
 * @author @xsomnus666_xiawenye★
 * @since 2019/7/24 0024 9:46
 * - 才需学也,学需静也/非淡泊无以明志，非宁静无以致远
 */
public class UDPReceiver {

    public static byte[] HEADER = new byte[]{7, 7, 7, 7, 7, 7, 7, 7};

    public static void main(String[] args) {
        try {
            DatagramSocket datagramSocket = new DatagramSocket(9090);

            byte[] buf = new byte[1024];
            DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length);

            datagramSocket.receive(datagramPacket);

            final byte[] data = datagramPacket.getData();

            int index = HEADER.length;
            int responsePort = (((data[index++]) << 24) |
                    ((data[index++] & 0xff) << 16) |
                    ((data[index++] & 0xff) << 8) |
                    ((data[index] & 0xff)));

            System.out.println("接受端接收的数据是： " + new String(buf, 0, datagramPacket.getLength()));
            System.out.println("receiver.....");

            datagramSocket.close();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
